import React, { Component } from 'react';
import { connect } from 'react-redux';
import $ from 'jquery';
import {
    Alert,
    Breadcrumb,
    Button,
    Card,
    Col,
    Container,
    ListGroup,
    Modal,
    Row,
} from 'react-bootstrap';

import AddDbConnectorInner from '../../components/deploy/addDbConnector';
import {
    function_add_dbconnector,
    function_remove_db_connector,
    function_get_hosts,
    function_get_dbconnectors
  } from '../../actions/deploy';

class App extends Component {
    state = {
        errorFlg: false,
        errorMsg: "",
        selectedIndex: -1,
        showDelModal: false
    }

    componentDidMount(){
        if(this.props.canDeployConnect){
            this.initData();
        }
    }

    componentDidUpdate(prevProps){
        if (!prevProps.canDeployConnect && this.props.canDeployConnect){
            this.initData();
        }
    }

    static getDerivedStateFromProps (props, state) {
        let projectArr = Object.keys(props.projectList);
        if (props.roleList.indexOf(1) === -1) {
            return {
            errorFlg: true,
            errorMsg: "非管理员无权操作"
            };
        } else if (projectArr.length === 0) {
            return {
            errorFlg: true,
            errorMsg: "请先创建项目"
            };
        } else if (props.deployUrl === null) {
            return {
            errorFlg: true,
            errorMsg: "尚未设置客户端工具链接地址，点击<a href=\"" + URL.download_page + "\">这里</a>进行设置"
            };
        } else if (!props.canDeployConnect) {
            return {
            errorFlg: true,
            errorMsg: "无法连接到" + props.deployHost + "，请检查服务器配置"
            };
        } else {
            return {
            errorFlg: false,
            errorMsg: ""
            }
        }
    }

    initData(){
        let projectArr = Object.keys(this.props.projectList);
        if(projectArr.length > 0){
          function_get_hosts(this.props.deployUrl, projectArr.join(","), this.props.dispatch, () => { });
          function_get_dbconnectors(this.props.deployUrl, projectArr.join(","), this.props.dispatch, ()=>{});
        }
    }

    setShowDelModal () {
        this.setState({ showDelModal: true });
      }
    
    setHideDelModal () {
        this.setState({ showDelModal: false });
    }

    cleanForm () {
        $("#dbConnectName").val("");
        $("#host").val("");
        $("#username").val("");
        $("#password").val("");
        $("#isUseSsh").attr("checked", false);
        $("#showHostBox").css("display", "none");
        $("#connectorType").attr("disabled", false);
        $("#dbConnectName").attr("readonly", false);
        $("#projectId").attr("disabled", false);
        this.setState({
          selectedIndex: -1,
          showDelModal: false
        });
    }

    handleSelect (index) {
        this.setState({ selectedIndex: index });
        let item = this.props.dbconnectors[index];
        $("#projectId").val(item.projectId);
        $("#dbConnectName").val(item.dbConnectorName);
        $("#host").val(item.host);
        $("#port").val(item.port);
        $("#username").val(item.username);
        $("#password").val("");
        $("#connectorType").attr("disabled", true);
        $("#dbConnectName").attr("readonly", true);
        $("#isUseSsh").attr("checked", parseInt(item.isUseSsh) === 1);
        $("#showHostBox").css("display", parseInt(item.isUseSsh) === 1 ? "flex" : "none");
        $("#projectId").attr("disabled", true);
    }
    
    handleSubmit () {
        if (this.props.canDeployConnect) {
            $("#projectId").attr("disabled", false);
            let selectProject = parseInt($("#projectId").val());
            if (this.state.selectedIndex === -1) {
                for (let item of this.props.dbconnectors) {
                    if (item.projectId === selectProject && item.hostName === $("#hostName").val()) {
                    this.setState({
                        errorFlg: true,
                        errorMsg: "该数据库连接已存在"
                    });
                    return;
                    }
                }
            } else {
                $("#projectId").attr("disabled", true);
            }
            function_add_dbconnector(this.props.deployUrl, selectProject, () => {
                this.cleanForm();
                let projectArr = Object.keys(this.props.projectList);
                function_get_dbconnectors(this.props.deployUrl, projectArr.join(","), this.props.dispatch, () => {});
            });
        }
    }
    
    handleDelDbConnector () {
        let selectProject = parseInt($("#projectId").val());
        function_remove_db_connector(this.props.deployUrl, selectProject, () => {
            this.cleanForm();
            let projectArr = Object.keys(this.props.projectList);
            function_get_dbconnectors(this.props.deployUrl, projectArr.join(","), this.props.dispatch, ()=>{});
        });
    }

    render () {
        return (
            <Container>
                <Breadcrumb>
                    <Breadcrumb.Item href={URL.main_page}>主页</Breadcrumb.Item>
                    <Breadcrumb.Item active>数据库连接</Breadcrumb.Item>
                </Breadcrumb>
                <Row>
                    <Col sm={8}>
                        <Card className="addHostBox">
                            <Card.Header>
                                {this.state.selectedIndex === -1 ? "添加数据库链接" : "修改数据库链接"}
                            </Card.Header>
                            <Card.Body>
                                {this.state.errorFlg ?
                                <Alert variant="danger">
                                    <div dangerouslySetInnerHTML={{ __html: this.state.errorMsg }}></div>
                                </Alert>
                                :
                                <Alert variant="success">
                                { "注意：数据库连接信息保存在 "+this.props.deployHost+" 服务器上的 /usr/local/onlinetool/config 文件中，部署时将从该服务器连接到您配置的数据库" }
                                </Alert>
                                }
                                <AddDbConnectorInner />
                            </Card.Body>
                            {!this.state.errorFlg ?
                                <Card.Footer>
                                {this.state.selectedIndex >= 0 ?
                                    <Button className="delBtn" variant="outline-danger" block onClick={this.setShowDelModal.bind(this)}>删除数据库链接</Button>
                                    : null}
                                <Button variant="secondary" onClick={this.cleanForm.bind(this)}>
                                    取消
                                </Button>
                                <Button variant="primary" onClick={this.handleSubmit.bind(this)}>
                                    {this.state.selectedIndex === -1 ? "添加" : "保存"}
                                </Button>
                                </Card.Footer>
                            : null}
                        </Card>    
                    </Col>
                    <Col sm={4}>
                        <Card>
                            <Card.Header>数据库库连接</Card.Header>
                            <ListGroup className="listHosts" variant="flush">
                            {this.props.dbconnectors.map((item, key) => {
                                return (
                                    <ListGroup.Item key={key} onClick={this.handleSelect.bind(this, key)}>
                                    <div className="icon">&#xe853;</div>
                                    <div className="body">
                                        <span className="title">{this.props.projectList[item.projectId].name}/{item.dbConnectorName}</span>
                                        <span className="extend">{item.username}@{item.host}</span>
                                    </div>
                                    </ListGroup.Item>
                                )
                            })}
                            </ListGroup>
                        </Card>
                    </Col>    
                </Row>
                {this.state.showDelModal ?
                <Modal show={this.state.showDelModal} onHide={this.setHideDelModal.bind(this)}>
                    <Modal.Header closeButton>
                    <Modal.Title>删除数据库链接</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>你确定要删除{this.props.dbconnectors[this.state.selectedIndex].dbConnectorName}？</Modal.Body>
                    <Modal.Footer>
                    <Button variant="secondary" onClick={this.setHideDelModal.bind(this)}>
                        取消
                    </Button>
                    <Button variant="primary" onClick={this.handleDelDbConnector.bind(this)}>
                        删除
                    </Button>
                    </Modal.Footer>
                </Modal>
                : null}
            </Container>
        )
    }
}

function mapStateToProps (state) {
    return {
        deployUrl: state.deploy.deployUrl,
        deployHost: state.deploy.deployHost,
        canDeployConnect: state.deploy.canDeployConnect,
        projectList: state.project,
        dbconnectors: state.deploy.dbconnectors,
        roleList: state.account.roleList,
    }
  }
  
  export default connect(mapStateToProps)(App);